import React, { useState, useEffect } from 'react';
import useStore from '../../components/useStore';
import { 
  Button, Card, Form, notification, Input, Upload, DatePicker, 
  InputNumber, Modal, Spin, Divider, Row, Col 
} from 'antd';
import { DownloadOutlined, UploadOutlined, InfoCircleOutlined } from '@ant-design/icons';
import store from '../../untils/store';
import dayjs from 'dayjs';
import request from '../../untils/request';

const UpdateSales = () => {
  const { collapsed } = useStore();
  const { localUrl } = store();
  const [salesDetail, setSalesDetail] = useState({});
  const [salesForm] = Form.useForm();
  const [businessContractFile, setBusinessContractFile] = useState(null);
  const [technicalAgreementFile, setTechnicalAgreementFile] = useState(null);
  const [uploading, setUploading] = useState(false);

  // 文件上传前置处理
  const handleBeforeUpload = (fileType) => (file) => {
    // 验证文件类型和大小
    const isPDF = file.type === 'application/pdf';
    const isWord = file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    const isLt20M = file.size / 1024 / 1024 < 20;

    if (!isPDF && !isWord && !isExcel) {
      notification.error({ message: '仅支持PDF、Word和Excel文件格式' });
      return false;
    }
    
    if (!isLt20M) {
      notification.error({ message: '文件大小不能超过20MB' });
      return false;
    }

    switch(fileType) {
      case "business_contract":
        setBusinessContractFile(file);
        break;
      case "technical_agreement":
        setTechnicalAgreementFile(file);
        break;
    }
    return false;
  };

  const save = async () => {
    try {
      const values = await salesForm.validateFields();
      const formData = new FormData();
      setUploading(true);

      // 固定字段
      formData.append('id', salesDetail.id);

      // 仅包含允许修改的字段
      if (values.order_date) {
        formData.append('order_date', dayjs(values.order_date).format('YYYY-MM-DD'));
      }
      
      if (values.money !== undefined && values.money !== null) {
        formData.append('money', values.money);
      }
      
      if (values.remark !== undefined && values.remark !== null) {
        formData.append('remark', values.remark);
      }

      if (businessContractFile) {
        formData.append('business_contract', businessContractFile);
      } else if (salesDetail.business_contract) {
        formData.append('business_contract', salesDetail.business_contract);
      }

      if (technicalAgreementFile) {
        formData.append('technical_agreement', technicalAgreementFile);
      } else if (salesDetail.technical_agreement) {
        formData.append('technical_agreement', salesDetail.technical_agreement);
      }

      // 发送请求
      fetch("/admin/sales/updateOrder", {
        method: "POST",
        body: formData,
        headers:{
          Authorization: `Bearer ${JSON.parse(localStorage.getItem('user')).token}`
        }
      }).then(response => response.json())
        .then(data => {
          if (data.code === 200) {
            notification.success({ message: data.msg });
            // 更新本地数据显示
            setSalesDetail(prev => ({
              ...prev,
              order_date: values.order_date ? dayjs(values.order_date).format('YYYY-MM-DD') : null,
              money: values.money,
              remark: values.remark,
              // 更新文件信息（如果有新上传）
              business_contract: businessContractFile ? businessContractFile.name : prev.business_contract,
              technical_agreement: technicalAgreementFile ? technicalAgreementFile.name : prev.technical_agreement
            }));
            // 清除已上传文件状态
            setBusinessContractFile(null);
            setTechnicalAgreementFile(null);
          } else {
            notification.error({ message: data.msg || "更新失败" });
          }
          setTimeout(() => setUploading(false), 300);
        });
    } catch (errorInfo) {
      notification.error({ message: "请检查填写信息是否有误" });
      setUploading(false);
    }
  };

  useEffect(() => {
    // 获取ID参数
    const hash = window.location.hash.slice(1);
    const queryString = hash.split('?')[1];
    let id = null;
    
    if (queryString) {
      const queryParams = new URLSearchParams(queryString);
      id = parseInt(queryParams.get('id'));
    } else {
      notification.error({ message: "没有找到 id 参数" });
      return;
    }

    // 加载数据 - 修正请求参数以匹配后端接口要求
    request("/admin/sales/searchSales", {
      method: "POST",
      body: { 
        condition: { id },  // 按照后端要求包装在condition对象中
        pageSize: 1,        // 只需要一条数据
        offset: 0,
        includeCustomer: true  // 包含客户信息
      }
    }).then(data => {
        if (data.code === 200 && data.data && data.data.length > 0) {
          // 从数组中获取第一条数据
          const orderData = data.data[0];
          const formattedData = {
            ...orderData,
            order_date: orderData.order_date ? dayjs(orderData.order_date) : null,
            // 移除交货日期字段处理
          };
          setSalesDetail(formattedData);
          salesForm.setFieldsValue(formattedData);
        } else {
          notification.error({ message: "获取数据失败" });
        }
      })
      .catch(() => {
        notification.error({ message: "网络错误" });
      });
  }, []);

  return (
    <div style={{    
      height: "94%", 
      backgroundColor: `#F1F1F1`,
      right: "1%",
      top: "4vh",
      overflow: "hidden",
      backgroundSize: "100% 100%", 
      width: collapsed ? "94%" : "84%", 
      position: "absolute",  
      color: "white", 
      fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", 
          position: "relative", 
          width: "96%", 
          marginLeft: "2%", 
          backgroundColor: "", 
          display: "flex",
          textIndent: "1rem", 
          justifyContent: "flex-start", 
          alignContent: "flex-start", 
          flexWrap: "wrap"
        }}>
          <Card style={{ width: "100%", marginTop: "2vh" }}>
            <div style={{ maxHeight: "75vh", overflowY: "scroll" }}>
              <div>
                <Form style={{ width: "95%" }} form={salesForm}>
                  {/* 不可改动信息区域 */}
                  <h3 style={{ 
                    color: '#1890ff', 
                    margin: '24px 0 12px', 
                    fontSize: 16, 
                    display: 'flex', 
                    alignItems: 'center' 
                  }}>
                    <InfoCircleOutlined style={{ marginRight: 6 }} /> 不可改动信息
                  </h3>
                  <Divider />
                  
                  <Form.Item name="order_id" label="订单号">
                    <Input placeholder='订单号为空' disabled />
                  </Form.Item>
                  
                  <Form.Item name="total_number" label="数量">
                    <InputNumber
                      style={{ width: '100%' }}
                      disabled
                    />
                  </Form.Item>

                  {/* 可修改信息区域 */}
                  <h3 style={{ 
                    color: '#1890ff', 
                    margin: '24px 0 12px', 
                    fontSize: 16, 
                    display: 'flex', 
                    alignItems: 'center' 
                  }}>
                    <InfoCircleOutlined style={{ marginRight: 6 }} /> 可修改信息
                  </h3>
                  <Divider />
                  
                  <Form.Item name="order_date" label="订单日期">
                    <DatePicker />
                  </Form.Item>
                  
                  <Form.Item 
                    name="money" 
                    label="金额"
                    rules={[{
                      validator: (_, value) => {
                        if (!value && value !== 0) return Promise.resolve();
                        if (value.toString().replace(/[.]/, '').length > 15) {
                          return Promise.reject(new Error('金额总长度不能超过15位'));
                        }
                        return Promise.resolve();
                      }
                    }]}
                  >
                    <InputNumber
                      prefix="¥"
                      precision={2}
                      step={0.01}
                      formatter={v => v?.toString()}
                      parser={v => v.replace(/[^\d.]/g, '')}
                      style={{ width: '100%' }}
                      placeholder='金额最长为15位数（含小数点与小数）'
                    />
                  </Form.Item>
                  
                  <Form.Item name="remark" label="特殊备注">
                    <Input placeholder='特殊备注为空' />
                  </Form.Item>

                  {/* 附件上传区域（保持可编辑） */}
                  <h3 style={{ 
                    color: '#1890ff', 
                    margin: '24px 0 12px', 
                    fontSize: 16, 
                    display: 'flex', 
                    alignItems: 'center' 
                  }}>
                    <InfoCircleOutlined style={{ marginRight: 6 }} /> 附件上传（新上传的文件将覆盖旧文件）
                  </h3>
                  <Divider />
                  
                  <Row gutter={[16, 16]}>
                    <Col xs={24} sm={12}>
                      <Form.Item name="business_contract" label="商务合同">
                        {salesDetail.business_contract ? (
                          <div>
                            <a href={`${localUrl}${salesDetail.business_contract}`} target="_blank" rel="noopener noreferrer">
                              <Button icon={<DownloadOutlined />}>下载文件</Button>
                            </a>
                          </div>
                        ) : (
                          <div>没有上传商务合同</div>
                        )}
                        <Upload
                          maxCount={1}
                          beforeUpload={handleBeforeUpload('business_contract')}
                          onRemove={() => { setBusinessContractFile(null); return true; }}
                          fileList={businessContractFile ? [{
                            uid: businessContractFile.uid || Date.now().toString(),
                            name: businessContractFile.name,
                            status: 'done'
                          }] : []}
                        >
                          <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                        </Upload>
                      </Form.Item>
                    </Col>
                    
                    <Col xs={24} sm={12}>
                      <Form.Item name="technical_agreement" label="技术协议">
                        {salesDetail.technical_agreement ? (
                          <div>
                            <a href={`${localUrl}${salesDetail.technical_agreement}`} target="_blank" rel="noopener noreferrer">
                              <Button icon={<DownloadOutlined />}>下载文件</Button>
                            </a>
                          </div>
                        ) : (
                          <div>没有上传技术协议</div>
                        )}
                        <Upload
                          maxCount={1}
                          beforeUpload={handleBeforeUpload('technical_agreement')}
                          onRemove={() => { setTechnicalAgreementFile(null); return true; }}
                          fileList={technicalAgreementFile ? [{
                            uid: technicalAgreementFile.uid || Date.now().toString(),
                            name: technicalAgreementFile.name,
                            status: 'done'
                          }] : []}
                        >
                          <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                        </Upload>
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Form.Item>
                    <Button type='primary' onClick={save}>保存更改</Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
          </Card>
          
          {/* 上传加载模态框 */}
          <Modal
            open={uploading}
            centered
            closable={false}
            footer={null}
            maskClosable={false}
            width={400}
            bodyStyle={{ textAlign: 'center', padding: '30px 20px' }}
          >
            <Spin />
            <div style={{ marginTop: 20, fontSize: 16, fontWeight: 'bold', color: '#333' }}>
              保存中
            </div>
            <div style={{ marginTop: 10, color: '#666' }}>
              请勿关闭页面或进行其他操作
            </div>
          </Modal>
        </div>
      </div>
    </div>
  );
};

export default UpdateSales;

const styles = {
  kshcontainer: {
    width: "98%", 
    height: "95%", 
    position: "absolute", 
    top: "3%", 
    left: "1%", 
    backgroundColor: "white", 
    color: "black",
    borderRadius: "10px",
  },
};